---
category: Misc
created: '2021-02-01'
title: Convert URL parameters to object
updated: '2021-10-13'
---

**JavaScript version**

```js getUrlParams.js
const getUrlParams = (query) =>
    Array.from(new URLSearchParams(query)).reduce(
        (p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }),
        {}
    );
```

**TypeScript version**

```ts getUrlParams.ts
const getUrlParams = (query: string): Record<string, string> => (
    Array.from(new URLSearchParams(query)).reduce((p, [k, v]) => Object.assign({}, p, { [k]: p[k] ? (Array.isArray(p[k]) ? p[k] : [p[k]]).concat(v) : v }), {} as Record<string, string>)
);
```

**Examples**

```js examples.js
getUrlParams(location.search); // Get the parameters of the current URL

getUrlParams('foo=Foo&bar=Bar'); // { foo: "Foo", bar: "Bar" }

// Duplicate key
getUrlParams('foo=Foo&foo=Fuzz&bar=Bar'); // { foo: ["Foo", "Fuzz"], bar: "Bar" }
```
